import apiClient from './api'

export interface Job {
  id: string
  job_name: string
  description: string
  cron_expression: string
  executor_handler: string
  executor_params: string
  is_active: boolean
  created_at: string
  updated_at: string
  job_status: string
  timeout_seconds: number
  retry_count: number
  retry_interval: number
  route_strategy: string
  executor_block_strategy: string
  // 注意：以下字段后端暂时不支持，使用默认值
  last_execution_time?: string
  next_execution_time?: string
  execution_count?: number  // 默认为0
  success_count?: number    // 默认为0
  failure_count?: number    // 默认为0
}

export interface JobCreateRequest {
  job_name: string
  description?: string
  cron_expression: string
  executor_handler: string
  executor_params?: string
  is_active?: boolean
}

export interface JobUpdateRequest extends Partial<JobCreateRequest> {
  id: string
}

export interface JobExecutionHistory {
  id: string
  job_id: string
  execution_time: string
  status: 'SUCCESS' | 'FAILED' | 'RUNNING' | 'PENDING'
  duration?: number
  error_message?: string
  result?: any
}

export interface JobTrigger {
  executor_params?: Record<string, any>
  trigger_type?: 'manual' | 'auto' | 'api'
}

export interface JobListResponse {
  total: number
  jobs: Job[]
}

export const jobApi = {
  // 认证状态检查
  async checkAuthStatus(): Promise<{ isValid: boolean; user?: any; error?: string }> {
    try {
      const token = localStorage.getItem('access_token')
      if (!token) {
        return { isValid: false, error: '没有找到access_token' }
      }
      
      console.log('正在验证token有效性...', {
        token: token.substring(0, 20) + '...',
        tokenLength: token.length
      })
      
      const response = await apiClient.get('/auth/me')
      return { 
        isValid: true, 
        user: response,
        error: undefined
      }
    } catch (error: any) {
      console.error('认证状态检查失败:', {
        status: error.response?.status,
        message: error.message,
        data: error.response?.data
      })
      return { 
        isValid: false, 
        error: `认证失败: ${error.response?.status || 'Unknown'} - ${error.message}` 
      }
    }
  },

  // 测试API连接
  async testConnection(): Promise<{ message: string; user: any }> {
    const response = await apiClient.get('/auth/me')
    return {
      message: '连接成功',
      user: response
    }
  },

  // 获取任务列表
  async getJobs(params?: { 
    page?: number
    size?: number
    search?: string
    status?: string
  }): Promise<JobListResponse> {
    const queryParams = {
      skip: params?.page ? (params.page - 1) * (params.size || 20) : 0,
      limit: params?.size || 20,
      search: params?.search,
      job_status: params?.status,
    }
    const response: any = await apiClient.get('/scheduled-jobs', { params: queryParams })
    return {
      total: response.total || 0,
      jobs: response.items || []
    }
  },

  // 获取单个任务详情
  async getJob(jobId: string): Promise<Job> {
    const response: any = await apiClient.get(`/scheduled-jobs/${jobId}`)
    return response as Job
  },

  // 创建任务
  async createJob(jobData: JobCreateRequest): Promise<Job> {
    const response: any = await apiClient.post('/scheduled-jobs', jobData)
    return response as Job
  },

  // 更新任务
  async updateJob(jobData: JobUpdateRequest): Promise<Job> {
    const response: any = await apiClient.put(`/scheduled-jobs/${jobData.id}`, jobData)
    return response as Job
  },

  // 删除任务
  async deleteJob(jobId: string): Promise<void> {
    await apiClient.delete(`/scheduled-jobs/${jobId}`)
  },

  // 启用/禁用任务
  async toggleJobStatus(jobId: string, isActive: boolean): Promise<Job> {
    const endpoint = isActive ? `/scheduled-jobs/${jobId}/start` : `/scheduled-jobs/${jobId}/stop`
    const response: any = await apiClient.post(endpoint)
    // 需要重新获取任务信息
    return this.getJob(jobId)
  },

  // 手动执行任务
  async executeJob(jobId: string): Promise<{ execution_id: string; message: string }> {
    const triggerData: JobTrigger = {
      executor_params: {
        manual_trigger: true,
        trigger_time: new Date().toISOString()
      },
      trigger_type: 'manual'
    }
    const response: any = await apiClient.post(`/scheduled-jobs/${jobId}/trigger`, triggerData)
    return {
      execution_id: response.log_id || response.execution_id || 'exec_' + Date.now(),
      message: response.message || '任务触发成功'
    }
  },

  // 获取任务执行历史
  async getJobExecutionHistory(
    jobId: string, 
    params?: { 
      page?: number
      size?: number
    }
  ): Promise<{ total: number; executions: JobExecutionHistory[] }> {
    const queryParams = {
      skip: params?.page ? (params.page - 1) * (params.size || 20) : 0,
      limit: params?.size || 20,
    }
    const response: any = await apiClient.get(`/scheduled-jobs/${jobId}/logs`, { params: queryParams })
    return {
      total: response.total || 0,
      executions: response.items || []
    }
  },

  // 获取任务统计信息
  async getJobStats(): Promise<{
    total: number
    active: number
    inactive: number
    recent_executions: number
    success_rate: number
  }> {
    const response: any = await apiClient.get('/scheduled-jobs/statistics/overview')
    return {
      total: response.total_jobs || 0,
      active: response.active_jobs || 0,
      inactive: (response.total_jobs || 0) - (response.active_jobs || 0), // 计算非活跃任务数
      recent_executions: response.total_executions_today || 0,
      success_rate: response.success_jobs_today && response.total_executions_today 
        ? Math.round((response.success_jobs_today / response.total_executions_today) * 100)
        : 0
    }
  },

  // 获取可用的处理器列表
  async getAvailableHandlers(): Promise<string[]> {
    // 这个端点可能需要后端实现，暂时返回静态列表
    return [
      'sync_user_data',
      'cleanup_logs', 
      'backup_database',
      'send_notifications',
      'process_orders',
      'generate_reports'
    ]
  },

  // 验证Cron表达式
  async validateCronExpression(cronExpression: string): Promise<{
    valid: boolean
    next_run_times?: string[]
    error?: string
  }> {
    try {
      const response: any = await apiClient.post('/scheduled-jobs/validate-cron', {
        cron_expression: cronExpression
      })
      return response as { valid: boolean; next_run_times?: string[]; error?: string }
    } catch (error: any) {
      return {
        valid: false,
        error: error.message || '无效的Cron表达式'
      }
    }
  },
}

// 定时任务工具函数
export const jobUtils = {
  // 获取Cron表达式的可读描述
  getCronDescription(cronExpression: string): string {
    // 这里可以实现Cron表达式的解析逻辑
    // 或者调用后端API来获取描述
    const parts = cronExpression.split(' ')
    if (parts.length !== 5 && parts.length !== 6) {
      return '无效的Cron表达式'
    }
    
    // 简单的描述逻辑示例
    if (cronExpression === '0 0 * * *') return '每日午夜执行'
    if (cronExpression === '0 2 * * *') return '每日凌晨2点执行'
    if (cronExpression === '0 */6 * * *') return '每6小时执行一次'
    if (cronExpression === '0 0 */7 * *') return '每周执行一次'
    
    return cronExpression
  },

  // 格式化执行状态
  formatExecutionStatus(status: string): { color: string; text: string } {
    switch (status) {
      case 'SUCCESS':
        return { color: 'green', text: '成功' }
      case 'FAILED':
        return { color: 'red', text: '失败' }
      case 'RUNNING':
        return { color: 'blue', text: '运行中' }
      case 'PENDING':
        return { color: 'orange', text: '等待中' }
      default:
        return { color: 'default', text: status }
    }
  },

  // 格式化持续时间
  formatDuration(milliseconds: number): string {
    if (milliseconds < 1000) {
      return `${milliseconds}ms`
    }
    const seconds = Math.floor(milliseconds / 1000)
    if (seconds < 60) {
      return `${seconds}秒`
    }
    const minutes = Math.floor(seconds / 60)
    const remainingSeconds = seconds % 60
    return `${minutes}分${remainingSeconds}秒`
  },

  // 计算成功率
  calculateSuccessRate(successCount: number, totalCount: number): string {
    if (totalCount === 0) return '0%'
    return `${Math.round((successCount / totalCount) * 100)}%`
  },
}